<!--
 * @Descripttion: 人员审核
 * @version:
 * @Author: wl
 * @Date: 2020-05-28 09:11:17
 * @LastEditors: wl
 * @LastEditTime: 2020-08-11 14:12:20
-->


<template>
  <div>
    <page :asideShow="asideShow">
      <div slot="toolbar">
        <el-form :inline="true" :model="filters" label-width="90px" label-position="right">
          <el-form-item label="姓名：">
            <el-input
              v-model="filters.name"
              placeholder="请输入姓名"
              clearable
              @keydown.enter.native="handleQuery"
            ></el-input>
          </el-form-item>
          <el-form-item label="人员来源：">
            <el-select v-model="filters.registration" placeholder="请选择" @change="handleQuery" clearable>
              <el-option
                v-for="item in registOption"
                :key="item.DID"
                :label="item.name"
                :value="item.DID"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="选择小区:">
            <el-select v-model="filters.CID" filterable placeholder="请选择" clearable>
              <el-option
                v-for="item in villageList"
                :key="item.CID"
                :label="item.name"
                :value="item.CID"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="人员类型：">
            <el-select v-model="filters.type" placeholder="请选择" @change="handleQuery" clearable>
              <el-option
                v-for="item in personType"
                :key="item.DID"
                :label="item.name"
                :value="item.DID"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="审核状态:">
            <el-select v-model="filters.auditType" filterable placeholder="请选择" clearable>
              <el-option
                v-for="item in statusOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="起始时间：">
            <el-date-picker
              class="normal"
              v-model="filters.startTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间：">
            <el-date-picker
              class="normal"
              v-model="filters.endTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="房屋：">
            <el-row style="width: 35%">
              <el-col :span="6">
                <el-input v-model="filters.buildName">
                  <span slot="suffix">栋</span>
                </el-input>
              </el-col>
              <el-col :span="6">
                <el-input v-model="filters.unitName">
                  <span slot="suffix">单元</span>
                </el-input>
              </el-col>
              <el-col :span="6">
                <el-input v-model="filters.floorName">
                  <span slot="suffix">层</span>
                </el-input>
              </el-col>
              <el-col :span="6">
                <el-input v-model="filters.houseName">
                  <span slot="suffix">号</span>
                </el-input>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </div>
      <div slot="btnSearch">
        <el-button type="primary" @click="handleQuery('a')">查询</el-button>
      </div>
      <div slot="content">
        <el-table
          :header-cell-style="{ background: '#e7eaf0', color: '#606266' }"
          ref="selectBox"
          :data="pageResult"
          stripe
          v-loading="loading"
          style="width: 100%"
          element-loading-text="加载中..."
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column prop="photoS" label="人像" width="100" align="center">
            <template slot-scope="scope">
              <img
                :onerror="$errorImgUrl"
                :src="scope.row.photo ? getItemPhoto(scope.row.photo) : imgs"
                v-image-preview
                style="width: 50px; height: 50px"
              />
            </template>
          </el-table-column>
          <el-table-column prop="name" header-align="center" align="center" label="姓名" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="gender" label="性别" align="center" width="60">
            <template slot-scope="scope">
              <div>
                <span v-if="scope.row.gender == 1">女</span>
                <span v-if="scope.row.gender == 0">男</span>
              </div>
              <!-- <span>{{scope.row.gender}}</span> -->
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="电话" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="photoCheck == scope.row.photoCheck">
                {{ scope.row.phone }}
              </span>
              <span v-else>{{ hideOfString(scope.row.phone) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="idCard" label="身份证" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="photoCheck == scope.row.photoCheck">
                {{ scope.row.idCard }}
              </span>
              <span v-else>{{ hideOfString(scope.row.idCard) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="registrationS" label="数据来源" width="150" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.registration ? getSourceName(scope.row.registration) : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="typeS" label="人员类型" align="center" width="100" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ typeToName(scope.row.type) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="insertTime"
            header-align="center"
            align="center"
            label="提交时间"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span>{{ $format(scope.row.insertTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="CIDD" label="所在小区" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.CID ? getCIDName(scope.row.CID) : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="人员地址" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.address ? scope.row.address : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="auditType" label="状态" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <div>
                <span v-if="scope.row.auditType == 0" style="color: #f56c6c">审核不通过</span>
                <span v-if="scope.row.auditType == 1" style="color: #67c23a">审核通过</span>
                <span v-if="scope.row.auditType == 2" style="color: #e6a23c">未审核</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" header-align="center" align="center" width="250" label="操作">
            <template slot-scope="scope">
              <el-button
                type="warning"
                v-show="hasPerm('pass:approval:examine')"
                @click="
                  getCheckEncryption() ? get_sensitive_fields(scope.row, handleExam) : (isCheckEncryption = true)
                "
              >
                审核
              </el-button>
              <el-button
                type="danger"
                v-show="hasPerm('pass:approval:delete')"
                @click="getCheckEncryption() ? handleDelete(scope.row) : (isCheckEncryption = true)"
              >
                删除
              </el-button>
              <el-button
                type="primary"
                v-show="hasPerm('pass:approval:show')"
                @click="
                  getCheckEncryption() ? get_sensitive_fields(scope.row, checkPhoto) : (isCheckEncryption = true)
                "
              >
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 审核 -->
        <div v-if="dialogTableVisible">
          <el-dialog
            title="审核验证"
            :close-on-click-modal="false"
            :visible.sync="dialogTableVisible"
            @close="closeDialog('formPass')"
          >
            <div class="addUser" v-loading="loadingS">
              <Examine :formPass="formPass" :oneCID="oneCID" @getexam="closeDialog"></Examine>
            </div>
          </el-dialog>
        </div>
      </div>
      <div slot="footer">
        <el-button
          :disabled="selections.length === 0 && !hasPerm('pass:approval:delete')"
          type="danger"
          style="float: left"
          @click="batchDelete"
        >
          批量删除
        </el-button>
        <el-pagination
          layout="total, prev, pager, next, jumper"
          @current-change="refreshPageRequest"
          :current-page="pageRequest.page"
          :page-size="pageRequest.limit"
          :total="totalSize"
          style="float: right"
        ></el-pagination>
      </div>
      <el-dialog title="身份验证" :visible.sync="isCheckEncryption">
        <CheckEncryption @close="isCheckEncryption = false"></CheckEncryption>
      </el-dialog>
    </page>
    <el-dialog title="身份验证" :visible.sync="isCheckEncryption">
      <CheckEncryption @close="isCheckEncryption = false"></CheckEncryption>
    </el-dialog>
  </div>
</template>

<script>
import Camera from './comments/camera';
import Examine from './comments/examine';
import CheckEncryption from '@/components/CheckEncryption';
export default {
  components: {
    Camera,
    Examine,
    CheckEncryption
  },
  data() {
    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^^1[0-9]{10}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error('请输入合法的手机号'));
    };
    return {
      isCheckEncryption: false,
      errorImg: 'this.src="' + require('@/assets/imgs/houtai/wutu.png') + '"', //默认图片
      // 上传成功的图片
      addImgUrl: '',
      // 新增人员
      addDialogVisible: false,
      operation: true,
      // 小区列表
      villageList: [],
      // 数据来源
      source: [],
      dictList: '', //字典
      // 新增编辑
      form: {
        CID: '',
        name: '', //名称
        idCard: '', //身份证号
        nation: '', //民族
        nationality: '', //国籍
        gender: '', //
        political: '', // 政治面貌
        type: '', //  人员类型
        birthday: '', // 出生年月日
        auditType: 2, // 审核状态 类型表
        unConsistency: '', // 人户一致
        maritalStatus: '',
        earlyWarning: '', //是否预警
        educationType: '', // 学历
        photo: '', // 图片表
        status: '', // 是否删除,
        img: '',
        picture: '',
        address: ''
      },
      // 规则
      formRules: {
        name: [
          {
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          }
        ],
        idCard: [
          {
            required: true,
            message: '请输入身份证号码',
            trigger: 'blur'
          }
        ],

        nation: [
          {
            required: true,
            message: '请输入民族',
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            message: '请输入手机号码',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ],

        type: [
          {
            required: true,
            message: '人员类型必填',
            trigger: 'blur'
          }
        ],
        CID: [
          {
            required: true,
            message: '小区必选',
            trigger: 'blur'
          }
        ]
      },
      // 待审核
      loadingS: false,
      // 弹框
      dialogTableVisible: false,
      aside: false,
      asideShow: false,
      unitShow: false,
      pageResult: [],
      selections: [],
      photoCheck: 0,
      filters: {
        CID: '',
        startTime: '',
        endTime: '',
        auditType: 2,
        name: '', //姓名
        type: '', //人员类型
        registration: '', //人员来源
        sign: '', //人员标记类型

        auditStatus: '' //审核状态
      },
      pageRequest: {
        page: 1,
        limit: 10
      },
      columns: [],
      loading: false,
      totalSize: 0,
      registOption: [],
      signOption: [],
      statusOption: [
        {
          value: 0,
          label: '未通过'
        },
        // {
        //   value: 1,
        //   label: "通过"
        // },
        {
          value: 2,
          label: '未审核'
        }
      ],
      getCommunity: [],
      //
      CODES: [],
      // 人员类型
      personType: [],
      // 数据来源
      persionSource: [],
      // 审核
      // auditList: [],
      // 审核人员
      perID: '',
      perName: '',
      // 审核需要穿的参数
      formPass: {
        _id: '',
        CID: '', //小区ID
        PID: '', //人员ID
        photo: '', //要审核人的照片
        auditType: '', //是否通过
        auditPID: '', //审核人员
        idCard: '', //idcard
        describe: '', //审核说明
        name: '', //姓名
        type: '', //人员类型
        registration: '', //人员注册方式
        perID: '',
        perName: '',
        address: '',
        startTime: '',
        endTime: '',
        houser: '' //人员地址
      },
      imgs: require('@/assets/imgs/houtai/wutu.png'),
      oneCID: ''
    };
  },
  methods: {
    getSourceName(id) {
      let rs = this.source.find((it) => it.DID === id);
      return rs && rs.name ? rs.name : '-';
    },
    typeToName(type) {
      for (let index = 0; index < this.houseList.length; index++) {
        var item = this.houseList[index];
        if (type === item.DID) {
          return item.name;
        }
      }
      return '-';
    },
    getCIDName(CID) {
      let rs = this.villageList.find((it) => it.CID === CID);
      return rs && rs.name ? rs.name : '-';
    },
    // 审核点击事件
    closeDialog(row) {
      this.dialogTableVisible = false;
      this.handleQuery(row);
    },
    //查看
    checkPhoto(row) {
      if (row.photoCheck == this.photoCheck) {
        this.photoCheck = 0;
      } else {
        this.$nextTick(() => {
          //nextTick并不是用来监听DOM变更，它的作用是一次性更改数据，并且渲染DOM
          this.$set(this.pageResult, this.photoCheck - 1, row);
        });
        this.photoCheck = row.photoCheck;
      }
    },
    //名字脱敏
    formatName(name) {
      var newStr;
      if (name.length === 2) {
        newStr = name.substr(0, 1) + '*';
      } else if (name.length > 2) {
        var char = '';
        for (var i = 0, len = name.length - 2; i < len; i++) {
          char += '*';
        }
        newStr = name.substr(0, 1) + char + name.substr(-1, 1);
      } else {
        newStr = name;
      }
      return newStr;
    },
    //图片处理
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader();
        let imgResult = '';
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    },
    // 编辑添加图片
    async upLoad(param) {
      var imgup = '';
      await this.getBase64(param.file).then((res) => {
        imgup = res;
      });
      var paramd = {
        img: imgup
      };
      this.$api.imgAdd
        .addimgPer(paramd)
        .then((res) => {
          // this.imgURL = res.data;
          this.form.photo = res.id;
          // console.log("ddddsaa", res);
        })
        .catch((err) => {
          // console.log("上传失败", err);
        });
    },
    // 拼接图片
    getItemPhoto(id) {
      var url = this.global.baseUrlImage + 'avatar/' + id;
      return url;
    },
    handleAvatarSuccess(res, file) {
      this.addImgUrl = URL.createObjectURL(file.raw);
    },

    // 获取人员类型
    personTypeL() {
      var sign = sessionStorage.getItem('dictData');
      var signs = JSON.parse(sign);
      var cod = JSON.parse(sessionStorage.getItem('group'));
      this.CODES = cod.CODES;
      var userID = JSON.parse(sessionStorage.getItem('userID'));
      this.perID = userID._id;
      this.perName = userID.name;

      this.personType = signs.sys_person_type;
      // 数据来源
      this.persionSource = signs.sys_persion_source;
      // 审核
      // this.auditList = signs.sys_person_audit;
    },
    // 获取数据列表
    getList() {
      this.loading = true;
      let params = Object.assign(this.pageRequest, this.filters);

      let paramJson = JSON.stringify(params);

      this.$api.personPass.findPage(paramJson).then((res) => {
        if (res.code == 0) {
          this.loading = false;
          this.pageResult = res.data;
          this.totalSize = res.count;
          this.pageResult.map((item, index) => {
            item.photoCheck = index + 1;

            // 图片
          });
        } else {
          // this.pageResult=[];
          this.loading = false;
          this.$message({
            message: '操作失败, ' + res.msg,
            type: 'error'
          });
        }
      });
    },

    //审核
    handleExam(row) {
      this.formPass = Object.assign({}, row);
      // 判断是否存在楼栋信息 不存在则新增空数据
      if (this.formPass.houser && this.formPass.houser.length == 0) {
        this.formPass.houser[0] = {
          BID: '',
          CID: '',
          FID: '',
          HID: '',
          PHID: '',
          PID: '',
          UID: ''
        };
      }
      this.dialogTableVisible = true;
      this.formPass.auditType = 1; //是否通过
      this.formPass.auditPID = this.perID;
      this.formPass.perID = this.perID;
      this.formPass.perName = this.perName;
      this.formPass.describe = row.describe || '';

      // console.log("tupian",row)
      this.getCommunity.forEach((item) => {
        if (item.CID == row.CID) {
          this.oneCID = item.name;
          console.log('shenh', this.oneCID);
        }
      });
    },
    // 选择小区
    villageScarch() {
      this.getCommunity = this.$store.state.village.villageList;
    },

    // 查询
    handleQuery() {
      this.pageRequest.page = 1;
      this.getList();
      this.dialogTableVisible = false;
      this.dictList = JSON.parse(sessionStorage.getItem('dictData'));

      this.registOption = this.dictList.sys_persion_source;
      this.signOption = this.dictList.sys_person_sign;
      this.registOption.map((item) => {
        item.value = item.DID;
        item.name = item.name;
      });
      this.signOption.map((item) => {
        item.value = item.DID;
        item.name = item.name;
      });
    },

    //删除
    handleDelete(row) {
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          let params = {
            IDS: row.PID
          };
          var paramJson = JSON.stringify(params);
          this.$api.personnel.batchDelete(paramJson).then((res) => {
            if (res.code == 0) {
              this.$message({
                message: '删除成功',
                type: 'success'
              });
              this.getList();
            } else {
              this.$message({
                message: '操作失败, ' + res.msg,
                type: 'error'
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },

    // 批量删除
    batchDelete() {
      this.$confirm('确认删除选中用户吗？', '提示', 'warning')
        .then(() => {
          let selLength = this.selections.length;
          let totalLength = this.pageResult.length;
          let isReduce = selLength == totalLength ? true : false;
          let params = this.selections
            .map((item) => {
              return item.PID;
            })
            .join(',');
          this.$api.personnel
            .batchDelete({
              IDS: params
            })
            .then((res) => {
              if (res.code == 0) {
                this.$message.success('删除成功');
                if (isReduce) {
                  this.pageRequest.page--;
                }
                this.getList();
              } else {
                this.$message.error(res.msg);
              }
            });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    // 翻页
    refreshPageRequest(page) {
      this.pageRequest.page = page;
      this.getList();
    },
    // 批量选择
    handleSelectionChange(val) {
      this.selections = val;
    },
    // 小区查询
    getCommunityList() {
      this.villageList = this.$store.state.village.villageList;
    }
  },
  mounted() {
    this.filters.CID = localStorage.getItem('home_CID');
    let dictList = JSON.parse(sessionStorage.getItem('dictData'));
    this.houseList = dictList.sys_person_type;
    this.source = dictList.sys_persion_source;
    this.personTypeL();
    // this.getList();
    this.handleQuery();
    this.villageScarch();

    this.getCommunityList();
  }
};
</script>

<style lang='scss' scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
/*.addUser{width: 60%}*/

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  display: block;
}

.addform {
  margin: 0 auto;
  display: flex;
  width: 100%;
  flex-wrap: wrap;
  justify-content: space-between;

  .el-form-item {
    width: 48%;
  }

  .el-form-item__content {
    overflow: hidden;
    .el-cascader {
      width: 100%;
    }

    .el-select {
      width: 100%;
    }
  }
}

// .el-date-editor.el-input,
// .el-date-editor.el-input__inner {
//   // width: 100%;
// }
</style>
